package com.cfweb.api;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cfweb.controller.LoginHandler;
import com.cfweb.util.CloudFoundryClientUtil;
import com.cfweb.util.JsonUtil;
import com.cfweb.util.StringUtil;

public class SpaceApi {
	
	static Logger logger = Logger.getLogger(SpaceApi.class);
	
	
	/**
     * create a space in the org
     * @param session
     * @param orgName
     * @param spaceName
     * @return boolean
     * @throws Exception 
     */
	public static boolean create_space(HttpSession session, final String orgName, 
			final String spaceName) throws Exception {
		String orgId;
		orgId = UserApi.get_org_id(session, orgName);
		if (orgId.isEmpty()) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/spaces?async=true&inline-relations-depth=1";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", spaceName);
			params.put("organization_guid", orgId);
			CloudFoundryClientUtil.doCCPost(urlPath, params, session);
		} catch (Exception e) {
			throw e;
		}
		String userName = (String) session.getAttribute(LoginHandler.USERNAME);
		if (!"admin".equals(userName)) {
			UserApi.set_space_role(session, userName, orgName, spaceName, "SpaceManager");
			UserApi.set_space_role(session, userName, orgName, spaceName, "SpaceDeveloper");
		}
		return true;
	}
	
	/**
     * delete a space in the org
     * @param session
     * @param orgName
     * @param spaceName
     * @return boolean
     * @throws Exception 
     */
	public static boolean delete_space(HttpSession session,String orgName, String spaceName) throws Exception {
		String spaceId;
		spaceId = UserApi.get_space_id(session, orgName, spaceName);
		if (StringUtil.isEmpty(spaceId)) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/spaces/" + spaceId + "?async=false&recursive=true";
			CloudFoundryClientUtil.doCCDelete(urlPath, null, session);
		} catch (Exception e) {
			throw e;
		}
		return true;
	}
	
	/**
     * rename a space in the org
     * @param session
     * @param orgName
     * @param spaceName
     * @return boolean
     * @throws Exception 
     */
	public static boolean rename_space(HttpSession session,String orgName,
			String spaceName, String newName) throws Exception {
		String spaceId;
		spaceId = UserApi.get_space_id(session, orgName, spaceName);
		if (StringUtil.isEmpty(spaceId)) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/spaces/" + spaceId;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", newName);
			CloudFoundryClientUtil.doCCPut(urlPath, params, session);	
		} catch (Exception e) {
			throw e;
		}
		return true;
	}
	
	/**
     * list spaces
     * @param session
     * @return List<Map<String,Object>>
     * @throws Exception 
     */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> list_spaces(HttpSession session) throws Exception {
        List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
        
        try {
            String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
            String urlPath = host + "/v2/spaces?async=true&inline-relations-depth=1";
            
            String content = CloudFoundryClientUtil.doCCGet(urlPath, null, session);
            
            Map<String, Object> data = JsonUtil.convertJsonToMap(content);
            List<Map<String, Object>> lr = (List<Map<String, Object>>) data.get("resources");
            String next_url = (String) data.get("next_url");
            while (next_url != null) {
                next_url = ApiCommonUtil.retriveAllPageResource(lr, next_url, session);
            }
            for (Map<String, Object> r : lr) {
                Map<String, Object> tmp = new HashMap<String, Object>();
                Map<String, Object> metadata = (Map<String, Object>) r.get("metadata");
                String guid = (String) metadata.get("guid");
                Map<String, Object> entity = (Map<String, Object>) r.get("entity");
                String spaceName = (String) entity.get("name");
                tmp.put("guid", guid);
                tmp.put("name", spaceName);
                res.add(tmp);
            }
        } catch (Exception e) {
            throw e;
        }
        return res;
	}
	
	/**
     * list spaces of a org
     * @param session
     * @param orgName
     * @return List<Map<String,Object>>
     * @throws Exception 
     */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> list_spaces_by_org(HttpSession session,String orgName) throws Exception{
		
	    List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
        String orgId = UserApi.get_org_id(session, orgName);
        if (StringUtil.isEmpty(orgId)) {
			return null;
		}
        try {
            String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
            String urlPath = host + "/v2/organizations/" + orgId + "/spaces?async=true";
            logger.debug(urlPath);
            String content = CloudFoundryClientUtil.doCCGet(urlPath, null, session);
            Map<String, Object> data = JsonUtil.convertJsonToMap(content);
            List<Map<String, Object>> lr = (List<Map<String, Object>>) data.get("resources");
            String next_url = (String) data.get("next_url");
            while (next_url != null) {
                next_url = ApiCommonUtil.retriveAllPageResource(lr, next_url, session);
            }
            for (Map<String, Object> r : lr) {
                Map<String, Object> tmp = new HashMap<String, Object>();
                Map<String, Object> metadata = (Map<String, Object>) r.get("metadata");
                String guid = (String) metadata.get("guid");
                Map<String, Object> entity = (Map<String, Object>) r.get("entity");
                String spaceName = (String) entity.get("name");
                tmp.put("guid", guid);
                tmp.put("orgName", orgName);
                tmp.put("name", spaceName);
                res.add(tmp);
            }
        } catch (Exception e) {
            throw e;
        }
        return res;
    }

	
}
